<?php

namespace App\Core;

class Request
{
    private static ?array $jsonData = null;

    public static function getMethod(): string
    {
        return $_SERVER['REQUEST_METHOD'];
    }

    public static function getPath(): string
    {
        return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    }

    public static function get(string $key, $default = null)
    {
        return $_GET[$key] ?? $default;
    }

    public static function post(string $key, $default = null)
    {
        $data = self::getJsonData();
        return $data[$key] ?? $_POST[$key] ?? $default;
    }

    public static function input(string $key, $default = null)
    {
        $data = self::getJsonData();
        return $data[$key] ?? $_GET[$key] ?? $_POST[$key] ?? $default;
    }

    public static function all(): array
    {
        $data = self::getJsonData();
        return array_merge($_GET, $_POST, $data);
    }

    public static function getJsonData(): array
    {
        if (self::$jsonData === null) {
            $input = file_get_contents('php://input');
            self::$jsonData = json_decode($input, true) ?? [];
        }
        return self::$jsonData;
    }

    public static function header(string $key, $default = null)
    {
        $key = 'HTTP_' . strtoupper(str_replace('-', '_', $key));
        return $_SERVER[$key] ?? $default;
    }

    public static function bearerToken(): ?string
    {
        $authorization = self::header('Authorization');
        
        if ($authorization && preg_match('/Bearer\s+(.*)$/i', $authorization, $matches)) {
            return $matches[1];
        }
        
        return null;
    }

    public static function validate(array $rules): array
    {
        $data = self::all();
        $errors = [];

        foreach ($rules as $field => $rule) {
            $value = $data[$field] ?? null;
            
            if (strpos($rule, 'required') !== false && empty($value)) {
                $errors[$field] = "{$field} 是必填项";
                continue;
            }

            if (strpos($rule, 'email') !== false && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                $errors[$field] = "{$field} 必须是有效的邮箱地址";
            }

            if (preg_match('/min:(\d+)/', $rule, $matches)) {
                $min = (int) $matches[1];
                if (strlen($value) < $min) {
                    $errors[$field] = "{$field} 长度不能少于 {$min} 位";
                }
            }

            if (preg_match('/max:(\d+)/', $rule, $matches)) {
                $max = (int) $matches[1];
                if (strlen($value) > $max) {
                    $errors[$field] = "{$field} 长度不能超过 {$max} 位";
                }
            }
        }

        if (!empty($errors)) {
            Response::error(implode(', ', $errors), 422);
        }

        return $data;
    }
}

